package worker

import (
	"context"
	"log"
	"sync"

	"image_demo/internal/api"
	"image_demo/internal/config"
	"image_demo/internal/downloader"
	"image_demo/internal/video"
)

// Pool 表示统一的worker池，处理图片和视频任务
type Pool struct {
	apiClient      *api.Client
	videoClient    *video.Client
	downloader     *downloader.Downloader
	taskChan       chan Task
	wg             sync.WaitGroup
	workerCount    int
	imageOutputDir string
	videoOutputDir string
	convertToWebP  bool
}

// NewPool 创建新的统一worker池
func NewPool(workerCount int, imageOutputDir, videoOutputDir string, convertToWebP bool) *Pool {
	return &Pool{
		apiClient:      api.NewClient(),
		videoClient:    video.NewClient(),
		downloader:     downloader.NewDownloader(convertToWebP),
		taskChan:       make(chan Task, workerCount*2),
		workerCount:    workerCount,
		imageOutputDir: imageOutputDir,
		videoOutputDir: videoOutputDir,
		convertToWebP:  convertToWebP,
	}
}

// NewPoolWithConfig 使用配置创建新的统一worker池
func NewPoolWithConfig(workerCount int, cfg *config.Config) *Pool {
	return NewPool(workerCount, cfg.Output.ImageDir, cfg.Output.VideoDir, cfg.Output.ConvertToWebP)
}

// Start 启动worker池
func (p *Pool) Start(ctx context.Context) {
	log.Printf("启动 %d 个统一worker...", p.workerCount)
	for i := 0; i < p.workerCount; i++ {
		p.wg.Add(1)
		go p.worker(ctx, i+1)
	}
}

// Submit 提交任务到worker池
func (p *Pool) Submit(ctx context.Context, task Task) bool {
	select {
	case p.taskChan <- task:
		log.Printf("任务已提交: %s (类型: %s)", task.APIURL, task.Type)
		return true
	case <-ctx.Done():
		log.Println("程序正在关闭，停止提交新任务")
		return false
	default:
		// worker pool已满，等待一下再重试
		log.Printf("worker pool已满，等待处理: %s (类型: %s)", task.APIURL, task.Type)
		select {
		case p.taskChan <- task:
			log.Printf("任务已提交: %s (类型: %s)", task.APIURL, task.Type)
			return true
		case <-ctx.Done():
			log.Println("程序正在关闭，停止提交新任务")
			return false
		}
	}
}

// Stop 停止worker池
func (p *Pool) Stop() {
	close(p.taskChan)
	p.wg.Wait()
}

// worker函数，处理API调用和媒体下载
func (p *Pool) worker(ctx context.Context, id int) {
	defer p.wg.Done()

	for {
		select {
		case task, ok := <-p.taskChan:
			if !ok {
				return
			}

			// 根据任务类型处理
			switch task.Type {
			case TaskTypeImage:
				p.handleImageTask(ctx, id, task)
			case TaskTypeVideo:
				p.handleVideoTask(ctx, id, task)
			default:
				log.Printf("[Worker %d] 未知任务类型: %s", id, task.Type)
			}

		case <-ctx.Done():
			log.Printf("[Worker %d] 接收到取消信号，退出", id)
			return
		}
	}
}

// handleImageTask 处理图片任务
func (p *Pool) handleImageTask(ctx context.Context, workerID int, task Task) {
	// 处理API调用
	log.Printf("[Worker %d] 开始处理图片API: %s", workerID, task.APIURL)
	imageURL, err := p.apiClient.Call(ctx, task.APIURL)
	if err != nil {
		log.Printf("[Worker %d] 图片API调用失败: %s, 错误: %v", workerID, task.APIURL, err)
		return
	}

	log.Printf("[Worker %d] 获取到图片URL: %s", workerID, imageURL)

	// 处理图片下载和转换
	if err := p.downloader.DownloadMedia(ctx, imageURL, p.imageOutputDir, downloader.MediaTypeImage); err != nil {
		log.Printf("[Worker %d] 图片处理失败: %s, 错误: %v", workerID, imageURL, err)
		return
	}

	log.Printf("[Worker %d] 图片任务完成: %s", workerID, task.APIURL)
}

// handleVideoTask 处理视频任务
func (p *Pool) handleVideoTask(ctx context.Context, workerID int, task Task) {
	// 处理视频API调用
	log.Printf("[Worker %d] 开始处理视频API: %s", workerID, task.APIURL)
	videoURL, err := p.videoClient.Call(ctx, task.APIURL)
	if err != nil {
		log.Printf("[Worker %d] 视频API调用失败: %s, 错误: %v", workerID, task.APIURL, err)
		return
	}

	log.Printf("[Worker %d] 获取到视频URL: %s", workerID, videoURL)

	// 处理视频下载
	if err := p.downloader.DownloadMedia(ctx, videoURL, p.videoOutputDir, downloader.MediaTypeVideo); err != nil {
		log.Printf("[Worker %d] 视频处理失败: %s, 错误: %v", workerID, videoURL, err)
		return
	}

	log.Printf("[Worker %d] 视频任务完成: %s", workerID, task.APIURL)
}
